package org.dh2580.delay.queue.bean.executor;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: hao.deng
 * @Date: 2019/5/14-下午8:00
 */
public class SimpleThreadFactory implements ThreadFactory {

    private AtomicInteger threadNo = new AtomicInteger(0);

    private String poolNamePrefix;

    private Boolean isDaemon;

    private ThreadGroup threadGroup;

    public SimpleThreadFactory(String poolNamePrefix, Boolean isDaemon) {

        this.poolNamePrefix = poolNamePrefix;

        this.isDaemon = isDaemon;

        threadGroup = System.getSecurityManager() != null ? System.getSecurityManager().getThreadGroup() : Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(threadGroup, r, poolNamePrefix + "-" + threadNo.getAndIncrement(), 0);

        //设置线程为守护线程
        thread.setDaemon(isDaemon);

        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }

        return thread;

    }
}
